import { useMount } from "@/hooks";
import { TreasuryGoods } from "@/types";
import { Card, CdnImage, Form, PrimaryButton, TextArea, TextInput, TextItem } from "@/ui-components";
import { Text, View } from "@tarojs/components";
import { useState } from "react";
import { useAppSelector } from "@/store/hooks";
import Taro from "@tarojs/taro";
import to from "await-to-js";
import { dialog } from "@/utils";
import { UserTreasury } from "@/store/treasurySlice";
import { DonateTreasuryGoodsParams, donateTreasuryGoods, getTreasuryGoodsDetail } from "../../network";
import './index.scss'

const onDonate = async (params: DonateTreasuryGoodsParams, treasuryGoods: TreasuryGoods, userTreasury ?: UserTreasury) => {
  if (!userTreasury) {
    Dialog.toast('用户信息错误')
    return
  }
  if (userTreasury.userScore < treasuryGoods.score) {
    Dialog.toast('积分不足')
    return
  }
  Dialogconfirm({
    content: `确定赠送商品${treasuryGoods.name}给${params.giftUserName}吗？`,
    onConfirm: async () => {
      params.treasuryGoodsId = treasuryGoods.treasuryGoodsId
      params.treasuryId = treasuryGoods.treasuryId
      const [err] = await to(donateTreasuryGoods(params))
      if (err) {
        Dialog.toast(err.message || '赠送失败，请稍后重试')
        return
      }
      Dialog.toast('赠送提交成功')
      Taro.navigateBack()
    }
  })
}


export default function TreasuryGoodsExchangePage() {

  const [treasuryGoods, setTreasuryGoods] = useState<TreasuryGoods | undefined>(undefined)
  const userTreasury = useAppSelector(state => state.treasury.userTreasury)
  const [params, setParams] = useState<Partial<DonateTreasuryGoodsParams>>({})

  useMount(async () => {
    const treasuryGoodsId = Number(Taro.getCurrentInstance().router?.params.treasuryGoodsId)
    if (Number.isNaN(treasuryGoodsId)) {
      Dialog.toast('参数错误')
      return
    }
    const [err, goods] = await to(getTreasuryGoodsDetail(treasuryGoodsId))
    if (err) {
      Dialog.toast(err.message || '获取商品信息失败')
      return
    }
    setTreasuryGoods(goods)
  })

  if (treasuryGoods) {
    return (
      <View className='treasuty-goods-exchange safe-bottom'>
        <Card className='treasury-goods-exchange-content'>
          <CdnImage src={treasuryGoods.image} className='treasury-goods-image p-normal border-radius-small' />
          <View className='text-title ph-normal'>{treasuryGoods.name}</View>
          <Form className='mt-small'>
            <TextItem value={userTreasury.userScore} label='我的积分' left />
            <TextItem value={treasuryGoods.score} label='消耗积分' left />
            <TextItem
              label='手续费'
              left
              renderRight={() => <View className='text-primary'><Text className='success'>20</Text>积分</View>}
            />
            <TextInput
              label='赠送人'
              placeholder='请输入赠送人的昵称'
              value={params.giftUserName}
              onChange={giftUserName => setParams({ ...params, giftUserName })}
            />
            <TextArea
              label='备注'
              placeholder='请输入赠送备注（选填）'
              value={params.note}
              onChange={note => setParams({ ...params, note })}
            />
          </Form>
        </Card>
        <PrimaryButton
          text='确认赠送'
          disabled={!params.giftUserName}
          onClick={() => onDonate(params as DonateTreasuryGoodsParams, treasuryGoods, userTreasury)}
        />
      </View>
    )
  }
}